//
//  Login.m
//  Speedater
//
//  Created by NgoThang on 12/28/11.
//  Copyright (c) 2011 __MyCompanyName__. All rights reserved.
//

#import "Login.h"
#import "Start.h"
#import "ForgotPassword.h"
#import "ChangePassword.h"
#import "Register.h"
#import "AppDelegate.h"
#import "JSON.h"

@interface Login (Private)

- (void)cleanup;

@end

@implementation Login (Private)

- (void)cleanup
{
    self.myScrollView = nil;
    self.loginButton = nil;
    self.registerButton = nil;
    self.forgotPasswordLabel = nil;
    self.usernameTextField = nil;
    self.passwordTextField = nil;
}

@end


@implementation Login

@synthesize myScrollView;
@synthesize usernameTextField, passwordTextField;
@synthesize loginButton, registerButton;
@synthesize forgotPasswordLabel;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [[UIApplication sharedApplication] setStatusBarHidden:YES];
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)dealloc
{
    //NSLog(@"LOGIN -> dealloc");
    [self cleanup];
    [super dealloc];
}

#pragma mark -
#pragma mark - Custom functions

- (void)hideKeyBoard
{
    [self.usernameTextField resignFirstResponder];
    [self.passwordTextField resignFirstResponder];
}

- (IBAction)loginButtonClick:(id)sender
{
    // hide keyboard
    [self hideKeyBoard];
    
    // validate form
    if (![usernameTextField.text length] || ![passwordTextField.text length]) {
        UIAlertView *alert = [[UIAlertView alloc] 
                              initWithTitle:nil 
                              message:NSLocalizedString(@"Please enter your username and password!", nil) 
                              delegate:nil 
                              cancelButtonTitle:NSLocalizedString(@"OK", nil) 
                              otherButtonTitles:nil];
        [alert show];	
        [alert release];
        return;
    }
    
    NSString *postString = [NSString stringWithFormat:@"op=login&username=%@&password=%@",usernameTextField.text, passwordTextField.text];
    NSData *postData = [postString dataUsingEncoding:NSUTF8StringEncoding];
    NSString *postLength = [NSString stringWithFormat:@"%d", [postString length]];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: [NSURL URLWithString:[[NSUserDefaults standardUserDefaults] stringForKey:@"url_preference"]]];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBody:postData];
    [request setTimeoutInterval:60.0];
    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    if (conn) {
        // init data    
        responseData = [[NSMutableData data ] retain];
        
        // loading
        UIWindow *theWindow = [UIApplication sharedApplication].keyWindow;
        HUD = [[MBProgressHUD alloc] initWithWindow:theWindow];
        [theWindow addSubview:HUD];
        HUD.delegate = self;
        [HUD show:YES];
    }
    [conn release];
}

- (IBAction)registerButtonClick:(id)sender
{
    Register *regis = [[Register alloc] init];
    [self.navigationController pushViewController:regis animated:YES];
    [regis release];
}

- (void)forgotPasswordLableClick:(id)sender
{
    ForgotPassword *forgotPassword = [[ForgotPassword alloc] init];
    [self.navigationController pushViewController:forgotPassword animated:YES];
    [forgotPassword release];
}

#pragma mark - Custom notifications

- (void)keyboardWillHide:(NSNotification *)noti
{    
    NSDictionary *userInfo = [noti userInfo];
    
    // restore size of scrollview
    NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSTimeInterval animationDuration;
    [animationDurationValue getValue:&animationDuration];

    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:animationDuration];
    [self.myScrollView setFrame:self.view.bounds];
    [UIView commitAnimations];

    keyboardIsShown = NO;
}
- (void)keyboardWillShow:(NSNotification *)noti
{
    // keyboard is already shown.
    if (keyboardIsShown) {
        return;
    }
    
    NSDictionary *userInfo = [noti userInfo];
    
    // get the size of the keyboard
    NSValue* aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    keyboardRect = [self.view convertRect:keyboardRect fromView:nil];
    CGFloat keyboardTop = keyboardRect.origin.y;
    CGRect newTextViewFrame = self.view.bounds;
    newTextViewFrame.size.height = keyboardTop - self.view.bounds.origin.y;
    
    // keyboard animation duration value
    NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSTimeInterval animationDuration;
    [animationDurationValue getValue:&animationDuration];
    
    // resize the scrollview
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:animationDuration];
    [self.myScrollView setFrame:newTextViewFrame];
    [UIView commitAnimations];
    
    keyboardIsShown = YES;
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    //NSLog(@"LOGIN -> viewDidLoad");
    // scroll view
    [self.myScrollView setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"background.png"]]];
    [self.myScrollView setContentSize:CGSizeMake(320, 480)];
    
    UITapGestureRecognizer *tgr = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(forgotPasswordLableClick:)] autorelease];
    [self.forgotPasswordLabel addGestureRecognizer:tgr];
    
    // register for keyboard notifications
    [[NSNotificationCenter defaultCenter] addObserver:self 
                                             selector:@selector(keyboardWillShow:) 
                                                 name:UIKeyboardWillShowNotification 
                                               object:self.view.window];
    [[NSNotificationCenter defaultCenter] addObserver:self 
                                             selector:@selector(keyboardWillHide:) 
                                                 name:UIKeyboardWillHideNotification 
                                               object:self.view.window];
    keyboardIsShown = NO;
    
    [super viewDidLoad];
}

- (void)viewDidUnload
{
    //NSLog(@"LOGIN -> viewDidUnload");

    // unregister for keyboard notifications while not visible.
    [[NSNotificationCenter defaultCenter] removeObserver:self 
                                                    name:UIKeyboardWillShowNotification 
                                                  object:nil]; 
    [[NSNotificationCenter defaultCenter] removeObserver:self 
                                                    name:UIKeyboardWillHideNotification 
                                                  object:nil]; 
    
    [super viewDidUnload];
}

- (void)viewWillAppear:(BOOL)animated
{
    //NSLog(@"LOGIN -> viewWillAppear");
    //NSLog(@"LOGIN -> viewControllers: %@", self.navigationController.viewControllers);
    
    // save state
    [AppDelegate saveState:0 withViewController:self];
    
    // navigation bar
    self.navigationController.navigationBar.hidden = YES;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark -
#pragma mark UITextFieldDelegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField 
{
    [textField resignFirstResponder];
    [self loginButtonClick:NULL];
	return YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField 
{
    BOOL isHideNav = self.navigationController.navigationBarHidden;
    [self.myScrollView setContentOffset:CGPointMake(0, textField.frame.origin.y - (self.myScrollView.frame.size.height/2) + (isHideNav ? 0 : 44)) animated:YES];
}

#pragma mark -
#pragma mark NSURLConnectionDelegete

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 
{
	[responseData setLength:0];
    
    // loading
	HUD.mode = MBProgressHUDModeDeterminate;
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
{
	[responseData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 
{
    // loading
    [HUD hide:YES];
    
    /* Error message */
	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil 
													message:NSLocalizedString(@"Unknown network error", nil)
												   delegate:self 
										  cancelButtonTitle:NSLocalizedString(@"OK", nil) 
										  otherButtonTitles:nil];
	[alert show];
	[alert release];	
    
    [responseData release];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection 
{
	NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
	
	NSMutableDictionary *results = [responseString JSONValue];
    //NSLog(@"%@", results);
    NSString *status = [results objectForKey:@"status"];
    if ([status isEqualToString:@"1"])
    {
        // store username and password for need case
        [[NSUserDefaults standardUserDefaults] setValue:[NSString stringWithString:usernameTextField.text] forKey:@"username"];
        [[NSUserDefaults standardUserDefaults] setValue:[NSString stringWithString:passwordTextField.text] forKey:@"password"];
        [[NSUserDefaults standardUserDefaults] synchronize];

        // if change password
        if ([[results objectForKey:@"active_code"] intValue]==1)
        {
            // goto start
            Start *start = [[Start alloc] init];
            [self.navigationController pushViewController:start animated:NO];
            [start release];
            // goto changepassword
            ChangePassword *changePassword = [[ChangePassword alloc] init];
            [self.navigationController pushViewController:changePassword animated:YES];
            [changePassword.oldPasswordTextField setText:passwordTextField.text];
            [changePassword.passwordTextField becomeFirstResponder];
            [changePassword release];
        }
        else 
        {
            // goto start
            Start *start = [[Start alloc] init];
            [self.navigationController pushViewController:start animated:YES];
            [start release];
        }
    }
    else 
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil 
                                                        message:NSLocalizedString(@"Login failure!", nil)
                                                       delegate:self 
                                              cancelButtonTitle:NSLocalizedString(@"OK", nil) 
                                              otherButtonTitles:nil];
        [alert show];
        [alert release];
    }

    // loading
    [HUD hide:YES];
    
    [responseData release];
	[responseString release];
}

#pragma mark -
#pragma mark MBProgressHUDDelegate methods

- (void)hudWasHidden:(MBProgressHUD *)hud {
    // Remove HUD from screen when the HUD was hidded
    [HUD removeFromSuperview];
    [HUD release];
    HUD = nil;
}

@end
